package crp.infra.ua;

import com.qwlabs.lang.S2;
import crp.core.analysis.domain.models.UserAgent;
import crp.core.analysis.domain.services.UserAgentParser;
import crp.core.shared.cache.CacheNames;
import io.quarkus.arc.DefaultBean;
import io.quarkus.cache.CacheResult;
import lombok.extern.slf4j.Slf4j;

import javax.enterprise.context.ApplicationScoped;

@ApplicationScoped
@DefaultBean
@Slf4j
public class UserAgentParserImpl implements UserAgentParser {
    @Override
    @CacheResult(cacheName = CacheNames.INFRA_USER_AGENT)
    public UserAgent parse(String raw) {
        UserAgent.UserAgentBuilder builder = UserAgent.builder();
        builder.raw(raw);
        if (S2.isEmpty(raw)) {
            return builder.build();
        }
        try {
            var ua = eu.bitwalker.useragentutils.UserAgent.parseUserAgentString(raw);
            builder.osName(ua.getOperatingSystem().getName());
            builder.osDeviceType(ua.getOperatingSystem().getDeviceType().toString());
            builder.osGroup(ua.getOperatingSystem().getGroup().getName());
            builder.osManufacturer(ua.getOperatingSystem().getManufacturer().getName());

            builder.browserName(ua.getBrowser().getName());
            builder.browserType(ua.getBrowser().getBrowserType().getName());
            builder.browserGroup(ua.getBrowser().getGroup().getName());
            builder.browserManufacturer(ua.getBrowser().getManufacturer().getName());
            builder.browserRenderingEngine(ua.getBrowser().getRenderingEngine().getName());
            builder.browserVersion(ua.getBrowserVersion().toString());
            return builder.build();
        } catch (Exception e) {
            LOGGER.warn(String.format("Can not parse user agent:%s", raw), e);
            return builder.build();
        }
    }
}
